//
//  HoverViewController.m
//  mosad_hw_fin
//
//  Created by student9 on 2020/12/24.
//  Copyright © 2020 student9. All rights reserved.
//

#import "HoverViewController.h"

@interface HoverViewController () {
    NSInteger today_count;
    NSInteger today_mid_count;
}

@end

@implementation HoverViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    __weak typeof(self) weakSelf = self;
    self.navigationController.navigationBar.hidden = YES;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0  blue:250/255.0 alpha:1];
    
    
    
    UIView *backgroundMine = [[UIView alloc]  initWithFrame:CGRectMake(0, 0, weakSelf.view.frame.size.width, weakSelf.view.frame.size.height / 2.4)];
    backgroundMine.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"backgroundMine.png" ]TransformtoSize:CGSizeMake(weakSelf.view.frame.size.width, weakSelf.view.frame.size.height / 2.4)]] ;
    [self.view addSubview:backgroundMine];
    
    UIView *borderMine = [[UIView alloc] initWithFrame: CGRectMake(0, 0, weakSelf.view.frame.size.width - 60, weakSelf.view.frame.size.height - 160)];
    borderMine.backgroundColor = [UIColor whiteColor];
    UIBezierPath * maskPath_borderMine = [UIBezierPath bezierPathWithRoundedRect:borderMine.bounds cornerRadius:30];
    CAShapeLayer * maskLayer_borderMine = [[CAShapeLayer alloc] init];
    maskLayer_borderMine.frame = borderMine.bounds;
    maskLayer_borderMine.path = maskPath_borderMine.CGPath;
    borderMine.layer.mask = maskLayer_borderMine;
    [self.view addSubview:borderMine];
    [borderMine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 60, weakSelf.view.frame.size.height - 160));
        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.centerY.equalTo(weakSelf.view.mas_centerY);
    }];
    
    _notlogin_pic = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    _notlogin_pic.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"warning.png"] TransformtoSize:CGSizeMake(200, 200)]];
    [self.view addSubview:_notlogin_pic];
    [_notlogin_pic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 200));
        make.centerX.mas_equalTo(borderMine.mas_centerX);
        make.centerY.mas_equalTo(borderMine.mas_centerY);
    }];
    
    _notlogin_label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    _notlogin_label.text = @"请先登录！";
    
    _notlogin_label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_notlogin_label];
    [_notlogin_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 40));
        make.centerX.mas_equalTo(borderMine.mas_centerX);
        make.top.mas_equalTo(self->_notlogin_pic.mas_bottom).offset(20);
    }];
    
    headimageModel *current_head_image = [headimageModel shareInstance];
    if ([current_head_image.ID isEqualToString:@"notlogin"] == YES) {
        _notlogin_pic.layer.hidden = NO;
        _notlogin_label.layer.hidden = NO;
    } else {
        _notlogin_pic.layer.hidden = YES;
        _notlogin_label.layer.hidden = YES;
        
       
        
        
        [self doJudgeIndexArray];
        
        
        
    }
    
    UIButton *back_btn;
    back_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    back_btn.frame = CGRectMake(0, 0, 40, 40);
    back_btn.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"leftarrow.png"] TransformtoSize:CGSizeMake(40, 40)]];
    [back_btn addTarget:self
                 action:@selector(back_to_mine:)
       forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:back_btn];
    [back_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(30);
        make.left.equalTo(weakSelf.view).offset(20);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
}

-(void) setHover {
    // 需要在这里做判断然后更新主界面
    
    NSInteger hover_count = _hoverTitle.count;
    if (hover_count > 4) {
        hover_count = 4;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        for (NSInteger i = 0; i < hover_count; i++) {
            UIView *hover_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width - 120) / 2, 180)];
            hover_view.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"cup.png"]  TransformtoSize:CGSizeMake((self.view.frame.size.width - 120) / 2, 180)]];
            UIBezierPath * maskPath_hoverview = [UIBezierPath bezierPathWithRoundedRect:hover_view.bounds cornerRadius:10];
            CAShapeLayer * maskLayer_hoverview = [[CAShapeLayer alloc] init];
            maskLayer_hoverview.frame = hover_view.bounds;
            maskLayer_hoverview.path = maskPath_hoverview.CGPath;
            hover_view.layer.mask = maskLayer_hoverview;
            [self.view addSubview:hover_view];
            [hover_view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake((self.view.frame.size.width - 120) / 2, 180));
                make.top.mas_equalTo(self.view.mas_top).offset(200 * (i / 2) + 120);
                make.left.mas_equalTo(self.view.mas_left).offset((self.view.frame.size.width - 120) * (i % 2) / 2 + 50 + 20 * (i % 2));
            }];
            
            UILabel *hover_str = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width - 120) / 2, 20)];
            hover_str.text = self->_hoverTitle[i];
            hover_str.textAlignment = NSTextAlignmentCenter;
            hover_str.font = [UIFont systemFontOfSize:20];
            [self.view addSubview:hover_str];
            [hover_str mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake((self.view.frame.size.width - 120) / 2, 20));
                make.top.mas_equalTo(self.view.mas_top).offset(200 * (i / 2) + 280);
                make.centerX.mas_equalTo(hover_view.mas_centerX);
            }];
            
            UILabel *detail_str = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width - 120) / 2, 10)];
            detail_str.text = self->_hoverExplain[i];
            detail_str.textAlignment = NSTextAlignmentCenter;
            detail_str.font = [UIFont systemFontOfSize:10];
            [self.view addSubview:detail_str];
            [detail_str mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake((self.view.frame.size.width - 120) / 2, 10));
                make.top.mas_equalTo(hover_str.mas_bottom).offset(5);
                make.centerX.mas_equalTo(hover_view.mas_centerX);
            }];
        }
    });
}

-(NSMutableArray *)arrayDataSource: (NSMutableArray *)index_array {
    NSMutableArray *jsonResult = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < [index_array count]; i++) {
        NSLog(@"print1: %ld", [index_array[i] longValue]);
        if ([index_array[i] intValue] == 0) {
            [jsonResult addObject:@"熬夜冠军"];
        } else if ([index_array[i] intValue] == 1) {
            [jsonResult addObject:@"养生大师"];
        } else if ([index_array[i] intValue] == 2) {
            [jsonResult addObject:@"卷王"];
        } else if ([index_array[i] intValue] == 3) {
            [jsonResult addObject:@"计划大师"];
        } else if ([index_array[i] intValue] == 4) {
            [jsonResult addObject:@"轻松生活"];
        } else if ([index_array[i] intValue] == 5) {
            [jsonResult addObject:@"猪猪生活"];
        }
    }
    return jsonResult;
}

-(NSMutableArray *)arrayDataSourceExplain: (NSMutableArray *)index_array {
    NSMutableArray *jsonResult = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < [index_array count]; i++) {
        NSLog(@"print2: %ld", [index_array[i] longValue]);
        if ([index_array[i] intValue] == 0) {
            [jsonResult addObject:@"今日深夜事件数量超过1"];
        } else if ([index_array[i] intValue] == 1) {
            [jsonResult addObject:@"今日深夜事件数量不超过1"];
        } else if ([index_array[i] intValue] == 2) {
            [jsonResult addObject:@"今日事件数量超过10"];
        } else if ([index_array[i] intValue] == 3) {
            [jsonResult addObject:@"今日事件数量超过5"];
        } else if ([index_array[i] intValue] == 4) {
            [jsonResult addObject:@"今日事件数量不超过5"];
        } else if ([index_array[i] intValue] == 5) {
            [jsonResult addObject:@"今日事件数量不超过2"];
        }
    }
    return jsonResult;
}

- (void) doJudgeIndexArray {
//    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    self->today_count = 0;
    self->today_mid_count = 0;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *nowdate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSWeekCalendarUnit | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear;
    comps = [calendar components:unitFlags fromDate:nowdate];
    NSLog(@"%ldmonth, %ldday, %ldweek", (long)[comps month], (long)[comps day], (long)[comps weekday]);
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    headimageModel *current_head_image = [headimageModel shareInstance];
    NSString *current_url_before = [current_head_image.host_str stringByAppendingString:@"Weekly/"];
    NSString *current_url = [current_url_before stringByAppendingString:current_head_image.ID];
    
    [manager GET:current_url
       parameters:nil
          headers:nil
         progress:^(NSProgress * _Nonnull downloadProgress) {
             //进度
         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             // 请求成功
             if ([responseObject[@"state"] boolValue]) {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     for (NSInteger i = 0; i < [responseObject[@"response"] count]; i++) {
                         if ([ [responseObject[@"response"] objectAtIndex:i][@"Week"] intValue] == (int)([comps weekday] - 1)) {
                             self->today_count += 1;
                             if ([ [responseObject[@"response"] objectAtIndex:i][@"Hour"] intValue] >= 0 && [ [responseObject[@"response"] objectAtIndex:i][@"Hour"] intValue] <= 6) {
                                 self->today_mid_count += 1;
                             }
                         }
                     }
                 });
             } else {
                 
             }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             // 请求失败
         }];
    AFHTTPSessionManager *manager2 =[AFHTTPSessionManager manager];
    manager2.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *current_url_before2 = [current_head_image.host_str stringByAppendingString:@"Onetime/"];
    NSString *current_url2 = [current_url_before2 stringByAppendingString:current_head_image.ID];
    
    [manager GET:current_url2
      parameters:nil
         headers:nil
        progress:^(NSProgress * _Nonnull downloadProgress) {
            //进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 请求成功
            if ([responseObject[@"state"] boolValue]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    for (NSInteger i = 0; i < [responseObject[@"response"] count]; i++) {
                        if ([ [responseObject[@"response"] objectAtIndex:i][@"Month"] intValue] == (int)[comps month] &&
                            [[responseObject[@"response"] objectAtIndex:i][@"Day"] intValue] == (int)[comps day]  ) {
                            self->today_count += 1;
                            if ([ [responseObject[@"response"] objectAtIndex:i][@"Hour"] intValue] >= 0 && [ [responseObject[@"response"] objectAtIndex:i][@"Hour"] intValue] <= 6) {
                                self->today_mid_count += 1;
                            }
                        }
                    }
                });
            } else {
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 请求失败
        }];
    AFHTTPSessionManager *manager3 =[AFHTTPSessionManager manager];
    manager3.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *current_url_before3 = [current_head_image.host_str stringByAppendingString:@"Daily/"];
    NSString *current_url3 = [current_url_before3 stringByAppendingString:current_head_image.ID];
    
    [manager GET:current_url3
      parameters:nil
         headers:nil
        progress:^(NSProgress * _Nonnull downloadProgress) {
            //进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 请求成功
            if ([responseObject[@"state"] boolValue]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    for (NSInteger i = 0; i < [responseObject[@"response"] count]; i++) {
                        self->today_count += 1;
                        if ([ [responseObject[@"response"] objectAtIndex:i][@"Hour"] intValue] >= 0 && [ [responseObject[@"response"] objectAtIndex:i][@"Hour"] intValue] <= 6) {
                            self->today_mid_count += 1;
                        }
                    }
                    NSMutableArray *index_array = [[NSMutableArray alloc] init];
                    NSLog(@"%ld, %ld", (long)self->today_count, (long)self->today_mid_count);
                    if (self->today_mid_count > 1) {
                        NSNumber *num = [[NSNumber alloc] initWithInt:0];
                        [index_array addObject:num];
                    }
                    if (self->today_mid_count <= 1) {
                        NSNumber *num = [[NSNumber alloc] initWithInt:1];
                        [index_array addObject:num];
                    }
                    if (self->today_count >= 10) {
                        NSNumber *num = [[NSNumber alloc] initWithInt:2];
                        [index_array addObject:num];
                    }
                    if (self->today_count > 5) {
                        NSNumber *num = [[NSNumber alloc] initWithInt:3];
                        [index_array addObject:num];
                    }
                    if (self->today_count <= 5) {
                        NSNumber *num = [[NSNumber alloc] initWithInt:4];
                        [index_array addObject:num];
                    }
                    if (self->today_count <= 2) {
                        NSNumber *num = [[NSNumber alloc] initWithInt:5];
                        [index_array addObject:num];
                    }
                    
                    self->_hoverTitle = [[NSMutableArray alloc] init];
                    self->_hoverTitle = [self arrayDataSource:index_array ];
                    self->_hoverExplain = [[NSMutableArray alloc] init];
                    self->_hoverExplain = [self arrayDataSourceExplain: index_array];
                    
                    [self setHover];
                });
            } else {
                
            }
//            dispatch_semaphore_signal(semaphore);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 请求失败
        }];
//    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    
}

- (void)back_to_mine:(UIButton *)buttonView {
    NSLog(@"back_to_mine");
    [self.navigationController popViewControllerAnimated:NO];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
